var bg = {};

if (chrome && chrome.extension) {
    bg = chrome.extension.getBackgroundPage();
}

function updateUI() {
    let data = bg.getData();
    // document.getElementById("info").innerHTML = JSON.stringify(data);
    document.getElementById("front_alpha").value = data.alpha;
    document.getElementById("background_x").value = data.x;
    document.getElementById("background_y").value = data.y;
    document.getElementById("scale").value = data.scale;
}

document.addEventListener('DOMContentLoaded', function () {
    updateUI();

    // 改变前景透明度
    document.getElementById("front_alpha").onchange = function (e) {
        let data = bg.getData();
        data.alpha = e.target.value;
        bg.setData(data);
        updateUI();
    };

    // x
    document.getElementById("background_x").onchange = function (e) {
        let data = bg.getData();
        data.x = e.target.value;
        bg.setData(data);
        updateUI();
    };

    // y
    document.getElementById("background_y").onchange = function (e) {
        let data = bg.getData();
        data.y = e.target.value;
        bg.setData(data);
        updateUI();
    };

    // scale
    document.getElementById("scale").onchange = function (e) {
        let data = bg.getData();
        data.scale = e.target.value;
        bg.setData(data);
        updateUI();
    };

    var fileEl = document.getElementById("input_file");
    fileEl.onchange = function (e) {
        const input = e.target;
        const files = e.target.files;
        if (files && files[0]) {
            const file = files[0];
            if (file.size > 1024 * 1024 * 3) {
                console.error("文件大小不能超过3M!");
                input.value = '';
                return false;
            } else {
                var reader = new FileReader();
                reader.readAsText(file);
                reader.onload = function (e) {
                    let data = bg.getData();
                    data.html = this.result;
                    data.file = e.target.value;
                    bg.setData(data);
                    updateUI();
                }
            }
        }
    }
});

